package com.rupecm.web;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.UploadedFile;

@ManagedBean(name = "arquivoBean")
@SessionScoped
public class ArquivoBean implements Serializable {

	private static final long serialVersionUID = -6567371185521699453L;
	private UploadedFile arquivo;  
	private String pastaTemp="C:\\tmp\\";

	
    public UploadedFile getFile() {
		return arquivo;
	}
	public void setFile(UploadedFile file) {
		this.arquivo = file;
	}
	
	public void upload(FileUploadEvent event){  
		FacesMessage msg = new FacesMessage("Arquivo '", event.getFile().getFileName() + "' foi salvo com sucesso!");  
        this.arquivo = event.getFile();
        try {
			copiar(event.getFile().getFileName(), event.getFile().getInputstream());
		} catch (IOException e) {
			e.printStackTrace();
		}
        FacesContext.getCurrentInstance().addMessage(null, msg);  
	    } 

	public void copiar(String fileName, InputStream in) throws IOException {
	try{
		OutputStream out = new FileOutputStream(new File(pastaTemp + fileName));
		
		int read = 0;
		byte[] bytes = new byte[1024];
		
		while ((read = in.read(bytes)) != -1) {
			out.write(bytes, 0, read);
		}

		in.close();
		out.flush();
		out.close();
		
			System.out.println("Arquivo copiado com sucesso!");
		} catch (IOException e) {
			System.out.println(e.getMessage());
		}
	}
	
	//getters and setters
	public UploadedFile getArquivo() {
		return arquivo;
	}
	public void setArquivo(UploadedFile arquivo) {
		this.arquivo = arquivo;
	}
	public String getPastaTemp() {
		return pastaTemp;
	}
	public void setPastaTemp(String pastaTemp) {
		this.pastaTemp = pastaTemp;
	}
	

}
